<?php

/**
 * This is the model class for table "inventory".
 *
 * The followings are the available columns in table 'inventory':
 * @property integer $id
 * @property integer $type_id
 * @property integer $quantity
 *
 * The followings are the available model relations:
 * @property TypeMakanan $type
 */
class Inventory extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Inventory the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'inventory';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('type_id, quantity', 'required'),
			array('type_id, quantity', 'numerical', 'integerOnly'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, type_id, quantity', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'type' => array(self::BELONGS_TO, 'TypeMakanan', 'type_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'type_id' => 'Tipe',
			'quantity' => 'Kuantitas',
		);
	}
	public function getJumlahDiperlukan(){
	$query= "SELECT SUM(quantity) FROM `makanan_konsumen`,`request_konsumen` WHERE `type_id` =".$this->type_id." AND `request_konsumen`.`id`=`makanan_konsumen`.`request_id` AND `request_konsumen`.`status`= 2";
	$command = Yii::app()->db->createCommand($query);
	
	$result= $command->query();
	$row = $result->read();
	if ($row['SUM(quantity)'] != NULL){
	return $row['SUM(quantity)'];}
	else{
		$row['SUM(quantity)'] = 0;
		return $row['SUM(quantity)'];
	}}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('type_id',$this->type_id);
		$criteria->compare('quantity',$this->quantity);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}